﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;

namespace SlideShowGenerator
{
    /// <summary>
    /// Configuration management class - loads, saves and provides access to the SS Generator options
    /// </summary>
    public static class Config
    {
        const string ConfigVersionNumber = "1.0";
        const string CONFIG_FILE = "SSGenerator.xml";
        const string DEFAULT_INPUT_DIR = @"C:\Temp";
        const string DEFAULT_OUTPUT_DIR = @"C:\Temp";
        const string DEFAULT_TEMP_DIR = @".\SSGen-Temp";
        const int DEFAULT_THUMBNAIL_SIZE = 300;

        private static FileInfo configFile;
        private static DirectoryInfo _inputDir;
        private static DirectoryInfo _outputDir;
        private static DirectoryInfo _tempDir;
        private static int _maxThumbnailSize;

        /// <summary>  </summary>
        public static int MaxThumbnailSize
        {
            get { return _maxThumbnailSize; }
            set { _maxThumbnailSize = value; }
        }

        /// <summary>  </summary>
        public static DirectoryInfo InputDir
        {
            get { return _inputDir; }
            set { _inputDir = value; }
        }

        /// <summary>  </summary>
        public static DirectoryInfo OutputDir
        {
            get { return _outputDir; }
            set { _outputDir = value; }
        }

        /// <summary>  </summary>
        public static DirectoryInfo TempDir
        {
            get { return _tempDir; }
            set { _tempDir = value; }
        }

        /// <summary>
        /// Set up the default configuration values
        /// </summary>
        public static void SetDefaults()
        {
            InputDir = new DirectoryInfo(DEFAULT_INPUT_DIR);
            OutputDir = new DirectoryInfo(DEFAULT_OUTPUT_DIR);
            TempDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), DEFAULT_TEMP_DIR));
            MaxThumbnailSize = DEFAULT_THUMBNAIL_SIZE;
        }

        /// <summary>
        /// Load the configuration file if it exists, otherwise set the default values
        /// </summary>
        /// <returns>true = Load Success (or defaults used), false = error reading config file (and defaults used)</returns>
        public static bool Load()
        {
            // Set up the configuration file path, based on the location of the SSGenerator executable.
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CONFIG_FILE);
            Trace.WriteLine("Searching for config file in application directory - " + configPath);
            configFile = new FileInfo(configPath);

            if (!configFile.Exists)
            {
                // No config file
                Trace.WriteLine("No config file currently exists, using default values");
                SetDefaults();
                Trace.WriteLine("Creating Configuration File.");
                Save();
                return true;
            }
            else
            {
                // Config File exists, load the values
			    Trace.WriteLine( "Config File Found: Config Path = " + configFile.FullName );

                try
                {
                    XmlDocument xmlConfig;
                    XmlTextReader configReader;
                    XmlNode en;					// temp xml Element used during processing

                    // Setup the reader and load the configuration file
                    configReader = new XmlTextReader(configFile.FullName);
                    configReader.WhitespaceHandling = WhitespaceHandling.None;
                    configReader.MoveToContent();

                    Trace.WriteLine("Loading Config File");
                    xmlConfig = new XmlDocument();
                    xmlConfig.Load(configReader);
                    configReader.Close();

                    Trace.WriteLine("Locating SSGeneratorConfig/Thumbnails Node.");
                    en = xmlConfig.SelectSingleNode("SSGeneratorConfig/Thumbnails");
                    _maxThumbnailSize = System.Convert.ToInt16(en.Attributes.GetNamedItem("MaxSize").Value);
                    Trace.WriteLine("Max Thumbnail Size = " + MaxThumbnailSize);

                    Trace.WriteLine("Locating SSGeneratorConfig/Directories Node.");
                    en = xmlConfig.SelectSingleNode("SSGeneratorConfig/Directories");
                    _inputDir = new DirectoryInfo(en.Attributes.GetNamedItem("Input").Value);
                    _outputDir = new DirectoryInfo(en.Attributes.GetNamedItem("Output").Value);
                    _tempDir = new DirectoryInfo(en.Attributes.GetNamedItem("Temp").Value);
                    Trace.WriteLine("Input Dir = " + InputDir);
                    Trace.WriteLine("Output Dir = " + OutputDir);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Error reading config file: Exception: " + ex);
                    return false;
                }
            }
            
           return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static bool Save()
        {
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("SSGeneratorConfig",new XAttribute("Version", ConfigVersionNumber),
                    new XElement("Thumbnails",
                        new XAttribute("MaxSize", _maxThumbnailSize)
                    ),
                    new XElement("Directories",
                        new XAttribute("Input", _inputDir),
                        new XAttribute("Output", _outputDir),
                        new XAttribute("Temp", _tempDir)
                    )
                )
            );

            doc.Save(configFile.FullName);

            return true;
        }
    }
}
